package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.common.Constants;
import com.neusoft.elmboot.mapper.RolePermissionMapper;
import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.mapper.UserRoleMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.po.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("myUserDetailsService")
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        System.out.println("------1.loadUserByUsername():userId="+userId);
        User user = userMapper.queryById(userId);

        // 数据库中查找用户相应的角色与权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        /*
        if(null != user && "13100000000".equals(user.getUsername())) {
//            authorities.add(new SimpleGrantedAuthority("ROLE_user"));
            authorities.add(new SimpleGrantedAuthority("GET /food/list"));
            user.setAuthorities(authorities);
        }*/
        // 查询用户id查询角色id列表
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userId",user.getId());
        UserRole userRole = userRoleMapper.selectByPrimaryKey(paramMap);
        if(null != userRole) {
            // 判断是否为：“超级管理员”
            if (Constants.SUPER_ADMIN_ROLE_ID == userRole.getRoleId()) {
                authorities.add(new SimpleGrantedAuthority("*"));
            } else {
                // 其余角色
                List<String> permApis = rolePermissionMapper.selectPermApiByRoleId(userRole.getRoleId());
                permApis.forEach(api -> authorities.add(new SimpleGrantedAuthority(api)) );
            }
            // 将权限的值保存到用户实体类中的authorities字段。
            user.setAuthorities(authorities);
        }



        return user;


//        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
